const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const serve = require('koa-static');
import { mapPath } from './utils/file';

import config from './config';

process.env.PORT = config.port;

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())

// logger
app.use(async (ctx, next) => {
  const start = new Date() as any;
  await next()
  const ms = (new Date() as any) - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})
// static
app.use(serve(mapPath('public')));

// routes
import shanbay from './routes/shanbay';
app.use(shanbay.routes(), shanbay.allowedMethods())


import baidu from './routes/baidu';
app.use(baidu.routes(), baidu.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
